<template>
  <div id="box">
    <div v-show="listbox">
      <el-container>
        <el-header>
          <!-- 管理员列表 -->
          <span>管理员列表</span>
          <p class="right return" id="" @click="backed">首页>部门列表</p>
        </el-header>
        <div class="headerbox">
          <el-button type="primary" @click="handleClose">删除选择</el-button>

          <el-button type="success" @click="refresh" :plain="true"
            >刷新</el-button
          >
                    <div class="dropdownBox" id="dropdownBox">
                        <el-select v-model="value1" placeholder="请选类别" @change="selectdep1"  :plain="true">
                            <el-option
                                    v-for="item in options1"
                                    :key="item.value1"
                                    :label="item.label1"
                                    :value="item.value1"
                            >
                            </el-option>
                        </el-select>
                    </div>
                    <div class="dpmBox">
                        <el-input placeholder="请输入" v-model="value5" clearable></el-input>
                    </div>
                    <el-button type="primary" icon="el-icon-search" @click="query">查询</el-button>
          <el-button type="success" class="right" @click="add"
            >新增管理员</el-button
          >
        </div>
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <span>确认删除吗</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false"
              >确 定</el-button
            >
          </span>
        </el-dialog>
        <!--表格内容-->
        <el-main>
          <div>
            <el-table
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                style="width: 5%"
              ></el-table-column>
              <el-table-column
                prop="managerName"
                label="用户名"
                style="width: 20%"
              ></el-table-column>
              <el-table-column
                prop="email"
                label="邮箱"
                style="width: 15%"
              ></el-table-column>
              <el-table-column
                prop="phone"
                label="手机号"
                style="width: 20%"
              ></el-table-column>
              <el-table-column
                prop="created"
                label="创建时间"
                style="width: 10%"
              ></el-table-column>
              <el-table-column
                prop="lastLoginTime"
                label="最后访问时间"
                style="width: 20%"
              ></el-table-column>
              <el-table-column
                prop="option"
                label="操作"
                width="300"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                  >
                    编辑</el-button
                  >
                  <!-- <el-button size="mini" @click="noLogin(scope.$index, scope.row)" v-show="nologin"> 禁止登录 </el-button>
                   <el-button size="mini" @click="canLogin(scope.$index, scope.row)" v-show="canlogin"> 运行登录 </el-button> -->
                  <!-- <el-switch
                    style="display: block  margin-left: 100px;"
                    v-model="value2"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="已允许"
                    inactive-text="已禁止"
                  >
                  </el-switch> -->
                  <el-switch
                    v-model="scope.row.on"
                    active-color="#F04134"
                    active-text="禁止"
                    on-value="1"
                    inactive-color="#00A854"
                    inactive-text="允许"
                    off-value="0"
                    @change="changeSwitch(scope.row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </div>
    <!-- 编辑 -->
    <div v-show="editAdmin">
      <el-container>
        <div id="content">
          <p class="jiben">基本信息</p>
          <ul class="left">
            <li>
              <p>名字</p>
              <el-input v-model="name" placeholder="用户名"></el-input>
            </li>

            <li>
              <p>登录密码</p>
              <el-input
                v-model="password"
                placeholder="设置系统登录密码"
              ></el-input>
            </li>
            <li>
              <p>确认密码</p>
              <el-input
                v-model="confirm"
                placeholder="再次输入登录密码"
              ></el-input>
            </li>
            <li>
              <p>头像照片</p>

              <div slot="tip" class="el-upload__tip">
                单上传头像图片大小不能超过 2MB!,仅支持JPG、JPEG、PNG格式
              </div>
              <!-- </el-upload> -->
              <div id="upload">
                <el-upload
                  class="avatar-uploader"
                  action="/image"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :plain="true"
                  name="uploadFile"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </li>
          </ul>
          <ul class="right">
            <li>
              <p>联系电话</p>
              <el-input v-model="phone" placeholder="联系电话"></el-input>
            </li>

            <li>
              <p>电子邮件</p>
              <el-input v-model="email" placeholder="电子邮件"></el-input>
            </li>
          </ul>
          <div id="jurisdictionBox">
            <p>权限选择</p>
            <!-- <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            > -->
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="checkedjurisdictions"
              @change="handleCheckedjurisdictionsChange"
            >
              <el-checkbox
                v-for="jurisdiction in jurisdictionOptions"
                :label="jurisdiction"
                :key="jurisdiction.name"
                >{{ jurisdiction.name }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
      </el-container>
      <div id="footBox">
        <div id="footer">
          <el-button type="info" @click="cancel()">取消</el-button>
          <el-button type="success" @click="keep" :plain="true">保存</el-button>
        </div>
      </div>
    </div>
    <!--分页-->
    <el-pagination
      :page-size="10"
      layout="prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!--page-size:每页显示条目个数
            pager-count：页码按钮的数量，当总页数超过该值时会折叠
            total	总条目数
        -->
  </div>
</template>

<script>
export default {
  name: "adminiStrator",
  data() {
    return {
      options1:[{value1:'managerName',label1:'用户名'},{value1:'phone',label1:'电话'},{value1:'email',label1:'邮箱'}],
      departement: "",
      //表格数据
      tableData: [
        {
          managerName: " ",
          email: "",
          phone: "",
          created: "",
          lastLoginTime: "",
        },
        {
          name: "一",
          on: "0",
        },
        {
          name: "二",
          on: "1",
        },
      ],
      value1:'',
      value5:'',
      multipleSelection: [],
      total: 0,
      currentPage: 1,
      checkAll: false, //权限选择
      imageUrl: "", //图片地址
      checkedjurisdictions: [],
      jurisdictions: [],
      isIndeterminate: true, //默认选中权限
      jurisdictionOptions: [], //权限列表
      privilegecount: [], //这个数据里面放选中权限的id
      listbox: true,
      editAdmin: false,
      noLogin: true,
      canlogin: false,
      name: "", //管理员姓名
      phone: "", //联系方式
      password: "", //登录密码
      email: "", //邮件
      confirm: "", //确认密码
      fileList: [], //上传文件列表
      dialogVisible: false, //提示框状态\
      userId: "", //用户id存在这里
      value: [], //存放的是所选权限的id
      value2: true, //这是禁止或允许登录d的状态
    };
  },
  methods: {
    // selectdep1(){
    //   // this.value1=this.options1.label1
      
    // },
    //返回首页
    backed() {
      this.$router.push({ path: "/index" });
    },

    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //补零规则
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    //将时间戳转换为日期格式
    format(shijianchuo) {
      //时间戳是整数，否则要parseInt转换
      var time = new Date(shijianchuo);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      return y + "-" + this.add0(m) + "-" + this.add0(d) + " ";
    },
    //  选中状态
    handleSelectionChange(val) {
      this.multipleSelection = [];
      val.forEach((item) => {
        this.multipleSelection.push(item.id); //把所有的id放进multipleSelection
      });
      console.log(this.multipleSelection);
    },
    handleClose() {
      //关闭弹出框
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            url: "/manager/delete",
            method: "post",
            data: { ids: this.multipleSelection },
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.check();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑
    handleEdit(index, row) {
      this.listbox = !this.listbox;
      this.editAdmin = !this.editAdmin;
      this.name = row.managerName;
      this.phone = row.phone;
      this.email = row.email;
      this.password = row.password;
      this.userId = row.id;
      this.imageUrl = row.imageUrl;

      //查询权限
      this.$axios({
        url: "/privilege/list",
      }).then((res) => {
        this.jurisdictionOptions = res.data.data;
        this.jurisdictions = res.data.data;
        //成功后用当前用户id查询已有权限
        this.$axios({
          url: "/manager/findById",
          params: { id: this.userId },
        }).then((res) => {
          let arr = [];
          this.privilegecount = res.data.data.privilege_ids;
          for (let i = 0; i < this.jurisdictionOptions.length; i++) {
            for (let j = 0; j < this.privilegecount.length; j++) {
              if (this.privilegecount[j] == this.jurisdictionOptions[i].id) {
                arr.push(this.jurisdictionOptions[i]);
              }
            }
          }
          this.checkedjurisdictions = arr;
        });
      });
    },
    keep() {
      this.$axios({
        url: "/manager/update",
        method: "post",
        data: {
          email: this.email,
          id: parseInt(this.userId),
          managerName: this.name,
          password: this.password,
          phone: this.phone,
          privilege_ids: this.value,
          imageUrl: this.imageUrl,
        },
      })
        .then((res) => {
          this.$message({
            showClose: true,
            message: "保存成功",
            type: "success",
          });
          this.listbox = !this.listbox;
          this.editAdmin = !this.editAdmin;
        })
        .catch((res) => {
          this.$message({
            showClose: true,
            message: "保存失败",
            type: "error",
          });
        });
    },
    //查看方法
    handleLookFor(index, row) {
      console.log(index, row);
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.check();
    },
    //  查询数据
    check() {
      this.$axios({
        url: "/manager/findByPage",
        method: "get",
        params: {
          page: this.currentPage,
          pageSize: 10,
        },
      }).then((res) => {
        if (res.data.code == 0) {
          var data = res.data.data.list;
          for (var i = 0; i < data.length; i++) {
            data[i].created = this.format(data[i].created);
            data[i].lastLoginTime = this.format(data[i].lastLoginTime);
          }
          this.tableData = data;
          this.total = res.data.data.total;
          console.log(res.data.code);
        } else {
          this.$router.push("/noResponse");
          if (res.data.code == 0) {
            this.$router.push("/administrator");
          }
        }
      });
    },
    add() {
      this.$router.push("/addAdmin");
    },
    refresh() {
      location.reload();
      this.$message({
        showClose: true,
        message: "刷新成功",
        type: "success",
      });
    },
    handleCheckAllChange(val) {
      //权限选择框方法
      console.log(val, this.jurisdictions);
      this.checkedjurisdictions = val ? this.jurisdictions : [];
      this.isIndeterminate = false;
    },
    handleCheckedjurisdictionsChange(value) {
      //权限选择框方法
      let arr1 = [];
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.jurisdictionOptions.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.jurisdictionOptions.length;
      //每勾选一个就往this.checkedjurisdictions加一个进去
      for (let i = 0; i < this.checkedjurisdictions.length; i++) {
        arr1.push(this.checkedjurisdictions[i].id);
        this.value = arr1;
      }
    },
    //取消按钮
    cancel() {   
      this.$confirm("修改还没保存，确定退出吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "取消成功!",
          });
          this.listbox = !this.listbox;
          this.editAdmin = !this.editAdmin;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    handlePreview(file) {
      console.log(file);
    },
    fileTest(ev) {
      var formData = new FormData();
      formData.append("uploadFile", ev.target.files);
      this.$axios({
        method: "post",
        url: "/image",
        data: formData,
      }).then((res) => {
        console.log(res);
      });
    },
    //搜索
    query(){
      this.$axios({
        url:'/manager/findManageByWhere',
        params:{
          name:this.value1,
          value:this.value5
        }
      }).then((res)=>{
        console.log(this.value1);
        console.log(this.value5);
        this.tableData=res.data.data

      })
    },
    //滑动开关控制登录
    changeSwitch(data) {
      if (data.on) {
        //如果data.on状态为true执行下面代码
        this.$axios({
          url: "/manager/noLogin",
          params: { id: data.id },
        })
          .then((res) => {
            this.$message({
              showClose: true,
              message: "已禁止登录",
              type: "success",
            });
          })
          .catch((res) => {
            console.log(res);
          });
      } else {
        //如果data.on状态为flase执行下面代码
        this.$axios({
          url: "/manager/canLogin",
          params: { id: data.id },
        })
          .then((res) => {
            this.$message({
              showClose: true,
              message: "已允许登录",
              type: "success",
            });
          })
          .catch((res) => {
            alert("失败");
          });
      }
    },
  },
  created() {
    this.check();
  },
};
</script>

<style scoped lang="less">
@fontcolor: #333;
@contentbgcolor: white;
* {
  padding: 0;
  margin: 0;
}
#dropdownBox{
  margin-top: 0px;
}
.return {
                color: #333;
                float: right;
                font-size: 18px;
                cursor: pointer;
            }

            .return:hover {
                color: #8cc5ff;
            }
#box {
  background: rgb(242, 242, 246);
}
.right {
  float: right;
  margin-right: 10px;
}
.headerbox {
  margin-top: 20px;

  button,
  div {
    float: left;
    margin-left: 10px;
  }

  .dropdownBox {
    margin-top: 10px;
  }
  .right {
    float: right;
  }
  
}

.el-header,
.el-footer {
  background-color: white;
  color: @fontcolor;
  text-align: center;
  line-height: 60px;
}

.el-header {
  margin-top: 10px;
  text-align: left;
}

.el-aside {
  background-color: @contentbgcolor;
  color: @fontcolor;
  text-align: center;
  line-height: 200px;
}

.el-main {
  margin-top: 10px;
  background-color: @contentbgcolor;
  color: @fontcolor;
  text-align: center;
  /* line-height: 160px;*/
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.el-pagination {
  float: right;
}

//编辑css
@contentbgcolor: white;
@margin: 10px;
ul {
  padding: 0;
}

a {
  text-decoration: none;
  color: #333333;
}

li {
  list-style: none;
  margin-top: 15px;

  p {
    margin: 0;
  }
}

#box {
  background:white;
}

.el-container {
  margin: 0;
  padding: 0;
}

.el-header {
  margin-top: 20px;
  background-color: rgb(242, 242, 246);
  color: #333;
  text-align: left;
  line-height: 60px;
  font-size: 20px;

  .right {
    float: right;
    margin-right: 10px;
  }
}

#content {
  background: @contentbgcolor;
  margin-top: 10px;

  .jiben {
    margin-left: 10px;
  }

  .left {
    float: left;
    margin-left: @margin;
    #upload {
      width: 178px;
      height: 178px;
      border: 1px dashed #6b6767;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #cfa1a1;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #587397;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .right {
    float: right;
    margin-right: @margin;
  }

  .el-input,
  .el-select {
    width: 610px;
    height: 50px;
  }
}

#footBox {
  width: 100%;
  height: 350px;
  background: white;
}

#footer {
  margin-left: 43%;
  height: 200px;

  .el-button {
    float: left;
    margin-top: 100px;
  }
}
#jurisdictionBox {
  width: 300px;
  height: 200px;
  float: right;
}
</style>